﻿using Microsoft.Web.WebView2.Core;

namespace QQGroupAlbumDownloader
{
    public partial class FrmBrowser : Form
    {
        private readonly string _groupId;

        public string Cookie { get; private set; }

        public string Token { get; private set; }

        public string QZoneToken { get; private set; }

        public string Uin { get; private set; }

        public FrmBrowser(string groupId)
        {
            _groupId = groupId;
            InitializeComponent();
        }

        private async void FrmBrowser_Load(object sender, EventArgs e)
        {
            await webView21.EnsureCoreWebView2Async(null);
            webView21.Source = new Uri($"https://h5.qzone.qq.com/groupphoto/index?inqq=1&groupId={_groupId}");
            webView21.CoreWebView2.WebResourceResponseReceived += CoreWebView2_WebResourceResponseReceived;
        }

        private void CoreWebView2_WebResourceResponseReceived(object sender, CoreWebView2WebResourceResponseReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(Token))
            {
                return;
            }
            if (e.Request.Uri.StartsWith(
                    "https://h5.qzone.qq.com/proxy/domain/u.photo.qzone.qq.com/cgi-bin/upp/qun_list_album_v2"))
            {
                var url = new Uri(e.Request.Uri);
                var queryParams = System.Web.HttpUtility.ParseQueryString(url.Query);

                Token = queryParams["g_tk"];
                QZoneToken = queryParams["qzonetoken"];
                Uin = queryParams["uin"];
                Cookie = e.Request.Headers.GetHeader("cookie");
            }

        }
    }
}
